/**
 * 版权所有：厦门市巨龙信息科技有限公司
 * Copyright 2023 Xiamen Dragoninfo Eng. Co. Ltd.
 * All right reserved.
 */
package com.github.alfred.database.adapter.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.github.alfred.database.DatabaseAdapterHandler;
import com.github.alfred.database.adapter.IDatabaseAdapterProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

/**
 * 类说明
 *
 * @author chengh
 * @date 2023/9/15 13:35
 */
@Service
public class MySqlAdapterProvider implements IDatabaseAdapterProvider, InitializingBean {
    private static final Logger log= LoggerFactory.getLogger(MySqlAdapterProvider.class);
    public static final String SORT_FORMAT = " if(isnull(%s),%d,%d),  %s  %s ";


    @Override
    public String getSortNullsLast(String column, Sort.Direction direction) {
        return String.format(SORT_FORMAT, column, 1, 0, column, direction);
    }

    @Override
    public String getSortNullsFirst(String column, Sort.Direction direction) {
        return String.format(SORT_FORMAT, column, 0, 1, column, direction);
    }

    @Override
    public String strToTimestamp(String time) {
        if (StrUtil.isBlank(time)) {
            return null;
        }
        try {
            DateTime dateTime = DateUtil.parse(time, DatePattern.PURE_DATETIME_PATTERN);
            return String.format("'%s'", DateUtil.format(dateTime.toJdkDate(), DatePattern.NORM_DATETIME_PATTERN));
        } catch (Exception e) {
            log.warn(e.getMessage(), e);
        }
        return String.format("'%s'", time);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        DatabaseAdapterHandler.registerService(DbType.MYSQL.getDb(), this);
    }

}
